<template>
  <div class="add-clothing">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑衣服' : '添加衣服' }}</h2>
      <p>{{ isEdit ? '修改衣服信息' : '拍照或上传图片，记录你的每一件衣服' }}</p>
    </div>

    <el-card>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="clothing-form"
      >
        <!-- 图片上传 -->
        <el-form-item label="衣服图片" prop="images">
          <div class="upload-section">
            <el-upload
              v-model:file-list="fileList"
              :action="uploadAction"
              :headers="uploadHeaders"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              list-type="picture-card"
              multiple
              accept="image/*"
              :file-list="fileList"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
            <div class="upload-tips">
              <p>支持拍照或从相册选择，建议上传正面清晰照片</p>
              <p>支持 JPG、PNG 格式，单张图片不超过 10MB</p>
              <p v-if="uploading" class="upload-status">上传中... {{ uploadedCount }}/{{ totalUploadCount }}</p>
              <p v-if="uploadError" class="error-text">{{ uploadError }}</p>
            </div>
          </div>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 基本信息 -->
            <el-form-item label="衣服名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入衣服名称" />
            </el-form-item>

            <el-form-item label="品牌" prop="brand">
              <el-input v-model="form.brand" placeholder="请输入品牌名称" />
            </el-form-item>

            <el-form-item label="分类" prop="category_id">
              <el-select v-model="form.category_id" placeholder="请选择分类">
                <el-option
                  v-for="category in categories"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="颜色" prop="color">
              <div class="color-input">
                <el-input v-model="form.color" placeholder="请输入颜色" style="width: 200px;" />
                <el-color-picker v-model="form.color_hex" />
                <el-button
                  size="small"
                  type="primary"
                  :loading="analyzingColor"
                  @click="analyzeImageColor"
                  :disabled="!hasImages"
                >
                  {{ analyzingColor ? '分析中...' : '智能识别' }}
                </el-button>
              </div>
              <div class="color-tips" v-if="detectedColors.length > 0">
                <span>检测到的颜色：</span>
                <div class="detected-colors">
                  <div
                    v-for="(color, index) in detectedColors"
                    :key="index"
                    class="color-item"
                    :style="{ backgroundColor: color.hex }"
                    @click="selectDetectedColor(color)"
                    :title="`${color.name} (${color.hex})`"
                  ></div>
                </div>
              </div>
            </el-form-item>

            <el-form-item label="尺码" prop="size">
              <el-select v-model="form.size" placeholder="请选择尺码">
                <el-option label="XS" value="XS" />
                <el-option label="S" value="S" />
                <el-option label="M" value="M" />
                <el-option label="L" value="L" />
                <el-option label="XL" value="XL" />
                <el-option label="XXL" value="XXL" />
                <el-option label="其他" value="other" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="材质" prop="material">
              <el-input v-model="form.material" placeholder="如：棉、丝绸、羊毛等" />
            </el-form-item>

            <el-form-item label="价格" prop="price">
              <el-input-number
                v-model="form.price"
                :min="0"
                :precision="2"
                placeholder="请输入价格"
                style="width: 100%;"
              />
            </el-form-item>

            <el-form-item label="购买日期" prop="purchase_date">
              <el-date-picker
                v-model="form.purchase_date"
                type="date"
                placeholder="选择购买日期"
                style="width: 100%;"
              />
            </el-form-item>

            <el-form-item label="购买地点" prop="purchase_place">
              <el-input v-model="form.purchase_place" placeholder="如：商场、网店等" />
            </el-form-item>

            <el-form-item label="适用季节" prop="season">
              <el-select v-model="form.season" placeholder="请选择季节">
                <el-option label="春季" value="spring" />
                <el-option label="夏季" value="summer" />
                <el-option label="秋季" value="autumn" />
                <el-option label="冬季" value="winter" />
                <el-option label="四季" value="all" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="风格" prop="style">
          <el-radio-group v-model="form.style">
            <el-radio label="casual">休闲</el-radio>
            <el-radio label="formal">正式</el-radio>
            <el-radio label="business">商务</el-radio>
            <el-radio label="sport">运动</el-radio>
            <el-radio label="party">派对</el-radio>
            <el-radio label="vintage">复古</el-radio>
            <el-radio label="street">街头</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="适用场合" prop="occasions">
          <el-checkbox-group v-model="form.occasions">
            <el-checkbox label="work">工作</el-checkbox>
            <el-checkbox label="daily">日常</el-checkbox>
            <el-checkbox label="date">约会</el-checkbox>
            <el-checkbox label="party">聚会</el-checkbox>
            <el-checkbox label="travel">旅行</el-checkbox>
            <el-checkbox label="sport">运动</el-checkbox>
            <el-checkbox label="formal">正式场合</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="保养说明" prop="care_instructions">
          <el-input
            v-model="form.care_instructions"
            type="textarea"
            :rows="3"
            placeholder="如：手洗、干洗、不可漂白等"
          />
        </el-form-item>

        <el-form-item label="备注" prop="notes">
          <el-input
            v-model="form.notes"
            type="textarea"
            :rows="3"
            placeholder="其他备注信息"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="submitForm"
            :loading="loading"
            :disabled="uploading"
          >
            {{ isEdit ? '更新衣服' : '保存衣服' }}
          </el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="$router.go(-1)">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="dialogVisible" title="图片预览">
      <img :src="dialogImageUrl" alt="预览图片" style="width: 100%; max-height: 70vh; object-fit: contain;" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { clothingAPI, categoryAPI, uploadAPI } from '@/api'

const router = useRouter()
const route = useRoute()
const formRef = ref()
const loading = ref(false)
const uploading = ref(false)
const uploadError = ref('')
const uploadedCount = ref(0)
const totalUploadCount = ref(0)

// 文件列表和预览
const fileList = ref([])
const dialogVisible = ref(false)
const dialogImageUrl = ref('')

// 编辑模式
const isEdit = computed(() => !!route.params.id)
const clothingId = computed(() => route.params.id)

// 分类数据
const categories = ref([])

// 颜色识别相关
const analyzingColor = ref(false)
const detectedColors = ref([])
const hasImages = computed(() => fileList.value.length > 0)

// 上传配置
const uploadAction = ref(`http://localhost:7002/api/v1/upload/image`)
const uploadHeaders = ref({
  Authorization: `Bearer ${localStorage.getItem('token')}`
})

// 颜色名称映射
const colorNameMap = {
  '#FFFFFF': '白色',
  '#000000': '黑色',
  '#FF0000': '红色',
  '#00FF00': '绿色',
  '#0000FF': '蓝色',
  '#FFFF00': '黄色',
  '#FF00FF': '紫色',
  '#00FFFF': '青色',
  '#808080': '灰色',
  '#800000': '深红',
  '#008000': '深绿',
  '#000080': '深蓝',
  '#808000': '橄榄',
  '#800080': '紫红',
  '#008080': '青绿',
  '#C0C0C0': '银色',
  '#FFA500': '橙色',
  '#FFC0CB': '粉色',
  '#A52A2A': '棕色',
  '#FFFFE0': '浅黄',
}

// 表单数据
const form = reactive({
  name: '',
  brand: '',
  category_id: '',
  color: '',
  color_hex: '',
  size: '',
  material: '',
  price: null,
  purchase_date: '',
  purchase_place: '',
  season: '',
  style: '',
  occasions: [],
  care_instructions: '',
  notes: '',
  images: []
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入衣服名称', trigger: 'blur' }
  ],
  category_id: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  images: [
    {
      validator: (rule, value, callback) => {
        if (fileList.value.length === 0) {
          callback(new Error('请上传至少一张图片'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

// 图片上传相关方法
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url || file.response?.data?.url
  dialogVisible.value = true
}

const handleRemove = async (file) => {
  try {
    if (file.response?.data?.url) {
      // 调用删除接口（如果需要）
      await uploadAPI.delete(file.response.data.url)
    }
    // 从form.images中移除
    form.images = form.images.filter(img => img !== file.url)
    ElMessage.success('图片删除成功')
  } catch (error) {
    console.error('删除图片失败:', error)
    ElMessage.error('删除图片失败')
  }
}

// 上传成功处理
const handleUploadSuccess = (response, file) => {
  if (response.code === 200) {
    uploadedCount.value++
    file.url = 'http://127.0.0.1:7002'+response.data.url // 设置文件URL
    form.images.push('http://127.0.0.1:7002'+response.data.url) // 添加到表单数据中
    ElMessage.success('图片上传成功')

    if (uploadedCount.value === totalUploadCount.value) {
      uploading.value = false
    }
  } else {
    uploadError.value = response.message || '上传失败'
    ElMessage.error(uploadError.value)
  }
}

// 上传错误处理
const handleUploadError = (error) => {
  console.error('上传失败:', error)
  uploadError.value = error.message || '上传失败'
  ElMessage.error('图片上传失败')
  uploading.value = false
}

// 上传前验证
const beforeUpload = (file) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isJPGOrPNG) {
    ElMessage.error('只能上传 JPG/PNG 格式的图片!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('图片大小不能超过 10MB!')
    return false
  }

  uploading.value = true
  totalUploadCount.value++
  uploadError.value = ''

  return true
}

// 智能颜色识别
const analyzeImageColor = async () => {
  if (!hasImages.value) {
    ElMessage.warning('请先上传图片')
    return
  }

  try {
    analyzingColor.value = true
    detectedColors.value = []

    // 模拟颜色识别
    const mockColors = [
      { hex: '#FFFFFF', name: '白色' },
      { hex: '#000000', name: '黑色' },
      { hex: '#FF0000', name: '红色' },
      { hex: '#0000FF', name: '蓝色' },
      { hex: '#808080', name: '灰色' }
    ]

    const numColors = Math.floor(Math.random() * 3) + 1
    const selectedColors = []
    for (let i = 0; i < numColors; i++) {
      const randomColor = mockColors[Math.floor(Math.random() * mockColors.length)]
      if (!selectedColors.find(c => c.hex === randomColor.hex)) {
        selectedColors.push(randomColor)
      }
    }

    detectedColors.value = selectedColors
    ElMessage.success(`检测到 ${selectedColors.length} 种主要颜色`)
  } catch (error) {
    console.error('颜色识别失败:', error)
    ElMessage.error('颜色识别失败')
  } finally {
    analyzingColor.value = false
  }
}

// 选择检测到的颜色
const selectDetectedColor = (color) => {
  form.color = color.name
  form.color_hex = color.hex
  ElMessage.success(`已选择颜色：${color.name}`)
}

// 重置表单
const resetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
  fileList.value = []
  form.images = []
  detectedColors.value = []
  uploading.value = false
  uploadedCount.value = 0
  totalUploadCount.value = 0
  uploadError.value = ''
}

// 加载编辑数据
const loadClothingData = async () => {
  if (!isEdit.value) return

  try {
    loading.value = true
    const response = await clothingAPI.getDetail(clothingId.value)

    if (response.code === 200) {
      const data = response.data

      // 填充表单数据
      Object.assign(form, {
        name: data.name || '',
        category_id: data.category_id || '',
        color: data.color || '',
        color_hex: data.color_hex || '',
        brand: data.brand || '',
        price: data.price || '',
        purchase_date: data.purchase_date || '',
        season: data.season || '',
        style: data.style || '',
        material: data.material || '',
        size: data.size || '',
        status: data.status || 'available',
        notes: data.notes || '',
        tags: data.tags || [],
        images: data.images || [],
        occasions: data.occasions || []
      })

      // 处理图片
      if (data.images && data.images.length > 0) {
        fileList.value = data.images.map((url, index) => ({
          uid: index,
          name: `image-${index}`,
          status: 'success',
          url: url,
          response: {
            code: 200,
            data: { url }
          }
        }))
      }
    }
  } catch (error) {
    console.error('加载衣服数据失败:', error)
    ElMessage.error('加载衣服数据失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const submitForm = async () => {
  debugger
  if (!formRef.value) return

  try {
    // 验证表单
    await formRef.value.validate()

    // 检查是否有图片正在上传
    if (uploading.value) {
      ElMessage.warning('请等待图片上传完成')
      return
    }

    // 检查是否有上传失败的图片
    const failedUploads = fileList.value.filter(file =>
      file.status === 'fail' || (file.status === 'success' && !file.url)
    )
    if (failedUploads.length > 0) {
      ElMessage.warning('请先解决上传失败的图片')
      return
    }

    loading.value = true

    const submitData = {
      ...form,
      // 确保images是字符串数组
      images: form.images.filter(url => url && typeof url === 'string')
    }

    if (isEdit.value) {
      await clothingAPI.update(clothingId.value, submitData)
      ElMessage.success('衣服更新成功')
    } else {
      await clothingAPI.create(submitData)
      ElMessage.success('衣服添加成功')
    }

    router.push('/wardrobe')
  } catch (error) {
    console.error('提交失败:', error)
    if (error.errors) {
      ElMessage.error('请完善表单信息')
    } else {
      ElMessage.error(error.message || '提交失败')
    }
  } finally {
    loading.value = false
  }
}

// 加载分类列表
const loadCategories = async () => {
  try {
    const response = await categoryAPI.getList()
    if (response.code === 200) {
      categories.value = response.data || []
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 页面初始化
onMounted(() => {
  loadCategories()
  if (isEdit.value) {
    loadClothingData()
  }
})
</script>

<style scoped>
.add-clothing {
  max-width: 800px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 5px 0;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.clothing-form {
  padding: 20px;
}

.upload-section {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.upload-tips {
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
}

.upload-tips p {
  margin: 0;
}

.upload-status {
  color: #409EFF;
  font-weight: 500;
}

.error-text {
  color: #F56C6C;
  font-weight: 500;
}

.color-input {
  display: flex;
  align-items: center;
  gap: 10px;
}

.detected-colors {
  display: flex;
  gap: 8px;
  margin-top: 5px;
}

.color-item {
  width: 20px;
  height: 20px;
  border-radius: 3px;
  cursor: pointer;
  border: 1px solid #ddd;
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 100px;
}
</style>
